package second.graph;

public class Solution16 {
    int[] father;

    public int[] findRedundantConnection(int[][] edges) {
        int n = edges.length;
        father = new int[n + 1];
        for (int i = 0; i < n + 1; i++) {
            father[i] = i;
        }
        for (int[] edge : edges) {
            if (!same(edge[0], edge[1])) join(edge[0], edge[1]);
            else return edge;
        }
        return null;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}

